<?php


// 公共助手函数

use Symfony\Component\VarExporter\VarExporter;

/**
 * 求两个已知经纬度之间的距离,单位为米
 * @param lng1 $ ,lng2 经度
 * @param lat1 $ ,lat2 纬度
 * @return float 距离，单位米
 * @author www.Alixixi.com
 */
function getdistance($lng1, $lat1, $lng2, $lat2)
{
    // 将角度转为狐度
    $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;

    return $s;
}

function float_number($number)
{
    $number = intval($number);
    $length = strlen(intval($number));  //数字长度
    if ($length > 3) { //万单位
        //截取前俩为
        $str = substr_replace(strstr($number, substr($number, -2), ' '), '.', -1, 0) . "公里";
    } else {
        return $number . '米';
    }

    return $str . '米';
}

function build_field_option($name = null, $selected = null,$type = null)
{
    //获取选项列表
    $fields = \addons\qingdong\model\Field::getField($name,$type);
    $html = '<option value="">请选择'.$name.'</option>';
    foreach ($fields as $v) {
        if ($selected == $v) {
            $html .= "<option value='{$v}' selected='selected'>{$v}</option>";
        } else {
            $html .= "<option value='{$v}'>{$v}</option>";
        }
    }

    return $html;
}

//修改多维数组为一位数组
function modify_array($arr, $field1, $field2)
{
    $data = [];
    foreach ($arr as $v) {
        $data[$v[$field1] ?? ''] = $v[$field2] ?? '';
    }

    return $data;
}

//显示文件夹
function showdir($path)
{
    $dh = opendir($path);//打开目录
    $arr = [];
    while (($d = readdir($dh)) != false) {
        //逐个文件读取，添加!=false条件，是为避免有文件或目录的名称为0
        if ($d == '.' || $d == '..') {//判断是否为.或..，默认都会有
            continue;
        }
        if (is_dir($path . '/' . $d)) {//如果为目录
            $lowers = showdir($path . '/' . $d);//继续读取该目录下的目录或文件
            if ($lowers) {
                $arr = array_merge($arr, $lowers);
            }
        } else {
            $arr[] = $path . '/' . $d;
        }
    }

    return $arr;
}
//获取年度列表
function getYears(){

    $start=2020;
    $years=[];
    $toYear=date('Y');
    $end=date('Y')+1;
    for ($start;$start<=$end;$start++){
        if($start == $toYear){
            $years[]=[
                'id'=>$start,
                'name'=>$start.'年',
                'selected'=>'selected'
            ];
        }else{
            $years[]=[
                'id'=>$start,
                'name'=>$start.'年',
            ];
        }
    }
    return $years;
}

///随机字符串，字母＋数字
function genRandomString($len,$t=0)
{
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z"
    );

    $chars1= array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z"
    );

    $chars2 = array(
        "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    );
    $chars3 = array(
        "A", "B", "C", "D", "E", "F", "G", "O" ,
        "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z"
    );
    $chars4 = array(
        "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "1","2",
        "3", "4", "5", "6", "7", "8", "9"
    );

    if($t==1){

        $charsLen = count($chars1) - 1;

        shuffle($chars1);    // 将数组打乱

        $output = "";
        for ($i=0; $i<$len; $i++)
        {
            $output .= $chars1[mt_rand(0, $charsLen)];
        }

    }elseif($t==2){

        $charsLen = count($chars2) - 1;

        shuffle($chars2);    // 将数组打乱

        $output = "";
        for ($i=0; $i<$len; $i++)
        {
            $output .= $chars2[mt_rand(0, $charsLen)];
        }

    }elseif($t==3){

        $charsLen = count($chars3) - 1;

        shuffle($chars3);    // 将数组打乱

        $output = "";
        for ($i=0; $i<$len; $i++)
        {
            $output .= $chars3[mt_rand(0, $charsLen)];
        }

    }elseif($t==4){

        $charsLen = count($chars4) - 1;

        shuffle($chars4);    // 将数组打乱

        $output = "";
        for ($i=0; $i<$len; $i++)
        {
            $output .= $chars4[mt_rand(0, $charsLen)];
        }
    }else{

        $charsLen = count($chars) - 1;

        shuffle($chars);    // 将数组打乱

        $output = "";
        for ($i=0; $i<$len; $i++)
        {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
    }

    return $output;

}

//将表情进行转义  用于存储的时候
function emoji_encode($str){
    if(!is_string($str)) return $str;

    if(!$str || $str=='undefined') return '';



    $text = json_encode($str); //暴露出unicode

    $text = preg_replace_callback("/(\\\u[2def][0-9a-f]{3})/i",function($str){

        return addslashes($str[0]);

    },$text); //将emoji的unicode留下，其他不动，这里的正则比原答案增加了d，因为我发现我很多emoji实际上是\ud开头的，反而暂时没发现有\ue开头。

    return json_decode($text);
}
//将表情进行反转义  用于读取的时候
function emoji_decode($str){
    $text = json_encode($str); //暴露出unicode

    $text = preg_replace_callback('/\\\\\\\\/i',function($str){

        return '\\';

    },$text); //将两条斜杠变成一条，其他不动

    return json_decode($text);
}
//过滤emoji
function filter_Emoji($str)
{
    $str = preg_replace_callback(    //执行一个正则表达式搜索并且使用一个回调进行替换
        '/./u',
        function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },
        $str);

    return $str;
}
//获取编号
function get_num($type)
{
    return 'R' . date('Ymd') . rand(10000, 99999);
}


if (!function_exists('setTimes')) {

    /**
     * @param $times
     * @param string $type date|datetime|time
     * @return array|string
     */
    function setTimes($times, $type = 'date')
    {
        switch ($times) {
            case 'today':
                $today = date('Y-m-d');
                $todayend = date('Y-m-d');
                $result = [$today, $todayend];
                break;
            case 'yesterday':
                $yesterday = date('Y-m-d', strtotime('-1 day'));
                $result = [$yesterday, $yesterday];
                break;
            case 'tomorrow':
                $tomorrow = date('Y-m-d', strtotime('+1 day'));
                $result = [$tomorrow, $tomorrow];
                break;
            case 'thisweek':
                $thisweek_start = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")));
                $thisweek_end = date("Y-m-d", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y")));
                $result = [$thisweek_start, $thisweek_end];
                break;
            case 'lastweek':
                $lastweek_start = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1 - 7, date("Y")));
                $lastweek_end = date("Y-m-d", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7 - 7, date("Y")));
                $result = [$lastweek_start, $lastweek_end];
                break;
            case 'nextweek':
                $lastweek_start = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1 + 7, date("Y")));
                $lastweek_end = date("Y-m-d", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7 + 7, date("Y")));
                $result = [$lastweek_start, $lastweek_end];
                break;
            case 'thismonth':
                $thismonth_start = date("Y-m-d", mktime(0, 0, 0, date("m"), 1, date("Y")));
                $thismonth_end = date("Y-m-d", mktime(23, 59, 59, date("m"), date("t"), date("Y")));
                $result = [$thismonth_start, $thismonth_end];
                break;
            case 'lastmonth':
                $lastmonth_start = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 1, date("Y")));
                $lastmonth_end = date("Y-m-d", mktime(23, 59, 59, date("m"), 0, date("Y")));
                $result = [$lastmonth_start, $lastmonth_end];
                break;
            case 'nextmonth':
                $nextmonth_start = date("Y-m-d", mktime(0, 0, 0, date("m") + 1, 1, date("Y")));
                $nextmonth_end = date("Y-m-d", mktime(23, 59, 59, date("m") + 1, date("t"), date("Y")));
                $result = [$nextmonth_start, $nextmonth_end];
                break;
            case 'thisquarter':
                //本季度未最后一月天数
                $getMonthDays = date("t", mktime(0, 0, 0, date('n') + (date('n') - 1) % 3, 1, date("Y")));
                //本季度/
                $thisquarter_start = date('Y-m-d', mktime(0, 0, 0, date('n') - (date('n') - 1) % 3, 1, date('Y')));
                $thisquarter_end = date('Y-m-d', mktime(23, 59, 59, date('n') + (date('n') - 1) % 3, $getMonthDays, date('Y')));

                $result = [$thisquarter_start, $thisquarter_end];
                break;
            case 'lastquarter':
                //上季度未最后一月天数
                $getMonthDays = date("t", mktime(0, 0, 0, date('n') + (date('n') - 1) % 3 - 3, 1, date("Y")));
                $thisquarter_start = date('Y-m-d', mktime(0, 0, 0, date('n') - (date('n') - 1) % 3 - 3, 1, date('Y')));
                $thisquarter_end = date('Y-m-d', mktime(23, 59, 59, date('n') + (date('n') - 1) % 3 - 3, $getMonthDays, date('Y')));

                $result = [$thisquarter_start, $thisquarter_end];
                break;
            case 'nextquarter':
                //下季度未最后一月天数
                $getMonthDays = date("t", mktime(0, 0, 0, date('n') + (date('n') - 1) % 3 + 3, 1, date("Y")));
                $thisquarter_start = date('Y-m-d', mktime(0, 0, 0, date('n') - (date('n') - 1) % 3 + 3, 1, date('Y')));
                $thisquarter_end = date('Y-m-d', mktime(23, 59, 59, date('n') + (date('n') - 1) % 3 + 3, $getMonthDays, date('Y')));

                $result = [$thisquarter_start, $thisquarter_end];
                break;
            case 'thisyear':
                //今年
                $thisyear_start = date('Y') . '-1-1';
                $thisquarter_end = date('Y') . '-12-31';

                $result = [$thisyear_start, $thisquarter_end];
                break;
            case 'lastyear':
                //去年
                $lastyear_start = date('Y') . '-1-1';
                $lastyear_end = date('Y') . '-12-31';

                $result = [$lastyear_start, $lastyear_end];
                break;
            case 'nextyear':
                //下一年
                $nextyear_start = date('Y') . '-1-1';
                $nextyear_end = date('Y') . '-12-31';

                $result = [$nextyear_start, $nextyear_end];
                break;
            default:
                $times = explode(',', $times);
                $result = [$times[0] ?? date('Y-m-d'), $times[1] ?? date('Y-m-d')];
                break;

        }
        if ($type == 'date') {
            return $result;
        } elseif ($type == 'datetime') {
            $result[0] = date('Y-m-d H:i:s', strtotime($result[0]));
            $result[1] = date('Y-m-d H:i:s', strtotime($result[1]) + 86400 - 1);
            return $result;
        } elseif ($type == 'time') {
            $result[0] =strtotime($result[0]);
            $result[1] =strtotime($result[1]) + 86400 - 1;
            return $result;
        } else {
            return $result;
        }
    }

}

if (!function_exists('export_excel')){

    //导出excel
    function export_excel($title, $expTableData, $excel = 'export')
    {

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $excel . '.xlsx');
        header('Cache-Control: max-age=0');

        $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('导出文件'); //设置标题
        $obj->setActiveSheetIndex(0);
        $obj->getActiveSheet()->setTitle('导出文件');
        /* 循环读取每个单元格的数据 */
        $a = 'A';
        $currentSheet = $obj->getActiveSheet();
        foreach ($title as $key => $value) {
            //读取工作表1

            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
            //这里是设置单元格的内容
            $currentSheet->getCell($a . '1')->setValue($value);
            $a++;
        }

        //行数循环
        $b = 2;
        foreach ($expTableData as $k => $row) {
            $a = 'A';
            foreach ($row as $key => $value) {
                //这里是设置单元格的内容
                $currentSheet->getCell($a . $b)->setValue($value);
                $a++;
            }
            $b++;
        }

        $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);
        $fileName = $excel . date('YmdHis') . '.xlsx';

        $file_path = ROOT_PATH . 'public' . '/export/' . date('Y-m-d') . '/' . $fileName;
        // 创建文件夹
        $path_info = pathinfo($file_path);
        if ($path_info['dirname'] && !is_dir($path_info['dirname'])) {
            $result = create_dir($path_info['dirname']);
            if (false === $result) {
                return false;
            }
        }
        $PHPWriter->save($file_path);
        $datas['filePath'] = '/' . 'export/' . date('Y-m-d') . '/' . $fileName;
        $datas['fileName'] = $fileName;
        $datas['size'] = filesize('./' . 'export/' . date('Y-m-d') . '/' . $fileName);
        return $datas;
    }
}
if (!function_exists('create_dir')){
    /**
     * 创建文件夹，可以多级创建
     * @param string $filename 需要创建的文件夹路径
     * @return boolean
     */
    function create_dir($filename) {
        if (!is_dir($filename)) {
            create_dir(dirname($filename));

            return mkdir($filename, 0777);
        }

        return true;
    }

}

if (!function_exists('convertAmountToCn')){

    /**
     * 将数值金额转换为中文大写金额
     * @param $amount float 金额(支持到分)
     * @param $type   int   补整类型,0:到角补整;1:到元补整
     * @return mixed 中文大写金额
     */
    function convertAmountToCn($amount, $type = 1)
    {

        // 判断输出的金额是否为数字或数字字符串
        if (!is_numeric($amount)) {
            return "要转换的金额只能为数字!";
        }
        // 金额为0,则直接输出"零元整"

        if ($amount == 0) {
            return "人民币零元整";
        }
        // 金额不能为负数
        if ($amount < 0) {
            return "要转换的金额不能为负数!";
        }
        // 金额不能超过万亿,即12位
        if (strlen($amount) > 12) {
            return "要转换的金额不能为万亿及更高金额!";
        }
        // 预定义中文转换的数组
        $digital = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
        // 预定义单位转换的数组
        $position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元');
        // 将金额的数值字符串拆分成数组
        $amountArr = explode('.', $amount);
        // 将整数位的数值字符串拆分成数组
        $integerArr = str_split($amountArr[0], 1);
        // 将整数部分替换成大写汉字
        $result = '';
        $integerArrLength = count($integerArr);     // 整数位数组的长度
        $positionLength = count($position);         // 单位数组的长度
        for ($i = 0; $i < $integerArrLength; $i++) {
            // 如果数值不为0,则正常转换
            if ($integerArr[$i] != 0) {
                $result = $result . $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i];
            } else {
                // 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位
                if (($positionLength - $integerArrLength + $i + 1) % 4 == 0) {
                    $result = $result . $position[$positionLength - $integerArrLength + $i];
                }
            }
        }
        // 如果小数位也要转换
        if ($type == 0) {
            // 将小数位的数值字符串拆分成数组
            $decimalArr = str_split($amountArr[1], 1);
            // 将角替换成大写汉字. 如果为0,则不替换
            if ($decimalArr[0] != 0) {
                $result = $result . $digital[$decimalArr[0]] . '角';
            }
            // 将分替换成大写汉字. 如果为0,则不替换
            if ($decimalArr[1] != 0) {
                $result = $result . $digital[$decimalArr[1]] . '分';
            }
        } else {
            $result = $result . '整';
        }
        return $result;
    }

}